package com.jdew.thkj.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jdew.thkj.R;
import com.jdew.thkj.activity.LoginActivity;
import com.jdew.thkj.activity.TbProductDetailActivity;
import com.jdew.thkj.activity.WebViewActivity;
import com.jdew.thkj.bean.ZhaoshangBean;
import com.jdew.thkj.dialog.CommonDialog;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.manager.WrapContentLinearLayoutManager;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.onitemInterface.OnItemClickListener;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangyang on 2017/9/18.
 */

public class MainAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener {
    public List<ZhaoshangBean.DataBean.TbkUatmFavoritesItemGetResponseBean.ResultsBean.UatmTbkItemBean> dataList;
    private List<ZhaoshangBean.DataBean.TbkUatmFavoritesItemGetResponseBean.ResultsBean.UatmTbkItemBean> list;
    private LayoutInflater layoutInflater;
    private Context context;
    private View itemView;
    private OnItemClickListener mItemClickListener;
    //item类型
    public static final int ITEM_TYPE_HEADER = 0;
    public static final int ITEM_TYPE_CONTENT = 1;
    public static final int ITEM_TYPE_BOTTOM = 2;
    private BituiAdapter adapter;
    private int mHeaderCount = 0;
    private int mBottomCount = 0;//底部View个数
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private String token;
    private String mPid;
    private String ItemId;
    private String Adzoneid;
    private String Siteid;
    private String maType;

    //内容长度
    public int getContentItemCount() {
        return dataList.size();
    }

    @Override
    public void onClick(View v) {                              //item的点击事件
        if (mItemClickListener != null) {
            mItemClickListener.onItemClick((Integer) v.getTag());
        }
    }

    public void setItemClickListener(OnItemClickListener itemClickListener) {
        mItemClickListener = itemClickListener;
    }

    public MainAdapter(Context context, List<ZhaoshangBean.DataBean.TbkUatmFavoritesItemGetResponseBean.ResultsBean.UatmTbkItemBean> dataList) {
        this.context = context;
        this.dataList = dataList;
        layoutInflater = LayoutInflater.from(context);
        list = new ArrayList<>();
        adapter = new BituiAdapter(context, list);
        sp = context.getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        maType = sp.getString("SpareTwo", "");
        bitui();
    }

    @Override
    public int getItemViewType(int position) {
        int dataItemCount = getContentItemCount();
        if (mHeaderCount != 0 && position < mHeaderCount) {
            return ITEM_TYPE_HEADER;
        } else if (mBottomCount != 0 && position >= (mHeaderCount + dataItemCount)) {
            return ITEM_TYPE_BOTTOM;
        } else {
            return ITEM_TYPE_CONTENT;
        }
    }

    public void setDataList(List<ZhaoshangBean.DataBean.TbkUatmFavoritesItemGetResponseBean.ResultsBean.UatmTbkItemBean> dataList) {
        this.dataList = dataList;
        notifyDataSetChanged();
    }

    public void setDataAllList(List<ZhaoshangBean.DataBean.TbkUatmFavoritesItemGetResponseBean.ResultsBean.UatmTbkItemBean> dataList) {
        this.dataList.addAll(dataList);
        notifyDataSetChanged();
    }

    //头部 ViewHolder
    public class HeaderViewHolder extends RecyclerView.ViewHolder  {
        @Bind(R.id.bitui)
        RecyclerView bitui;
        @Bind(R.id.more)
        TextView more;

        HeaderViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        public void BindView(final RecyclerView.ViewHolder holder, int position) {
            bitui.setLayoutManager(new WrapContentLinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
            bitui.setAdapter(adapter);
            adapter.setItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    token = sp.getString("token", "");
                    mPid = sp.getString("mpid", "");
                    Siteid = sp.getString("Siteid", "");
                    Adzoneid = sp.getString("Adzoneid", "");
                    if (!RegexValidateUtils.isFastClick()) {
                      return;
                    }
                    if (sp.getString("userName", "").equals("")) {
                        Intent in = new Intent(context, LoginActivity.class);
                        context.startActivity(in);
                    } else if (token.equals("")) {
                        toset("授权失效,请联系客服");
                    } else if (mPid.equals(AppConfig.MPID)) {
                        toAdu();
                    } else {
                        ItemId = list.get(position).getNum_iid();
                        toDetail();
                    }
                }
            });
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == ITEM_TYPE_HEADER) {
            itemView = layoutInflater.inflate(R.layout.layout_header, parent, false);
            return new HeaderViewHolder(itemView);
        } else if (viewType == ITEM_TYPE_CONTENT) {
            itemView = layoutInflater.inflate(R.layout.product_list_item2, parent, false);
            itemView.setOnClickListener(this);
            return new MyViewHolder(itemView);
        }
        return null;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof MyViewHolder) {
            MyViewHolder myviewHolder = (MyViewHolder) holder;
            myviewHolder.BindView(holder, position);
            myviewHolder.itemView.setTag(position);
        } else if (holder instanceof HeaderViewHolder) {
            HeaderViewHolder headerViewHolder = (HeaderViewHolder) holder;
            headerViewHolder.BindView(holder, position);
            headerViewHolder.itemView.setTag(position);
        }
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.product)
        ImageView product;
        @Bind(R.id.name)
        TextView name;
        @Bind(R.id.price)
        TextView price;
        @Bind(R.id.before_price)
        TextView beforePrice;
        @Bind(R.id.quan)
        TextView quan;
        @Bind(R.id.earn)
        public TextView earn;
        @Bind(R.id.num)
        TextView num;
        @Bind(R.id.source)
        ImageView source;

        MyViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        public void BindView(RecyclerView.ViewHolder holder, int position) {
            DecimalFormat df = new DecimalFormat("0.00");
            String youhuiquan = null;
            String nowPrice;
            String manjian = null;
            String showPrice = null;
            String str = dataList.get(position).getCoupon_info();
            ((MyViewHolder) holder).beforePrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            if (dataList.get(position).getUser_type().equals("0")) {
                source.setImageResource(R.mipmap.tb);
            } else {
                source.setImageResource(R.mipmap.tm);
            }
            ((MyViewHolder) holder).beforePrice.setText("原价:" + dataList.get(position).getZk_final_price());
            if (null != str) {
//                quan.setVisibility(View.VISIBLE);
                youhuiquan = dataList.get(position) == null ? "0" : str.split("元")[1].replace("减", "");
                manjian = dataList.get(position).getCoupon_info() == null ? "0" : str.substring(1, str.lastIndexOf("减")).replace("元", "");
            } else {
                youhuiquan = "0";
                manjian = "0";
//                quan.setVisibility(View.INVISIBLE);
            }
            if (Double.parseDouble(dataList.get(position).getZk_final_price()) >= Double.parseDouble(manjian) && Double.parseDouble(youhuiquan)<=Double.parseDouble(dataList.get(position).getZk_final_price())) {
                showPrice = df.format(Double.parseDouble(dataList.get(position).getZk_final_price()) - Double.parseDouble(youhuiquan));
            } else {
                youhuiquan="0";
                showPrice = df.format(Double.parseDouble(dataList.get(position).getZk_final_price()));
            }
            String zhuan = df.format(Double.parseDouble(showPrice) * Double.parseDouble(dataList.get(position).getTk_rate()) / 100);
            dataList.get(position).setShowPrice(showPrice);
            ((MyViewHolder) holder).name.setText(dataList.get(position).getTitle());
            ((MyViewHolder) holder).num.setText("月销:" + dataList.get(position).getVolume());
            ((MyViewHolder) holder).price.setText(showPrice + "");
            if (maType.equals("") || maType.equals("1")) {
                earn.setVisibility(View.GONE);
            } else {
                earn.setVisibility(View.VISIBLE);
                if(maType.equals("0")){
                    ((MyViewHolder) holder).earn.setText("分享赚" + zhuan + "元");
                }else{
                    ((MyViewHolder) holder).earn.setText("分享赚" + df.format(Double.parseDouble(zhuan)/2) + "元");
                }
            }
            SpannableString spannableString= new SpannableString(price.getText().toString());
            RelativeSizeSpan sizeSpan = new RelativeSizeSpan(1.2f);
            spannableString.setSpan(sizeSpan, 0, price.getText().toString().indexOf("."), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            price.setText(spannableString);
            ((MyViewHolder) holder).quan.setText(dataList.get(position).getCoupon_info() == null ? "0元券" : youhuiquan+"元券");
             Glide.with(context).load(dataList.get(position).getPict_url()).into(product);
        }
    }

    public void bitui() {
        String timesamp=RegexValidateUtils.getTime13();
        String numsamp=RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetWillpush(1, RegexValidateUtils.getUniquePsuedoID(),timesamp,numsamp,MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp+numsamp+RegexValidateUtils.getUniquePsuedoID()+sp.getString("SignToken","")+"PageIndex1")).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<ZhaoshangBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(ZhaoshangBean bean) {
                list.clear();
                if (bean.isSuccess()) {
                    list.addAll(bean.getData().getTbk_uatm_favorites_item_get_response().getResults().getUatm_tbk_item());
                    adapter.setDataList(list);
                }
            }
        });
    }

    public void toAdu() {
        new CommonDialog.Builder((Activity) context)
                .setTitle("提示")
                .setMessage("设置默认推广位")
                .setPositiveButton("设置", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent in = new Intent(context, WebViewActivity.class);
                        in.putExtra("type", 2);
                        in.putExtra("url", "http://pub.alimama.com/");
                        context.startActivity(in);
                    }
                }).show();
    }

    public void toset(String message) {
        new CommonDialog.Builder((Activity) context)
                .setTitle("提示")
                .setMessage(message)
                .setMessageGravity()
                .setdialogPostive("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                    }
                }).show();
    }

    public void toDetail(){
        Intent intent = new Intent();
        Bundle b = new Bundle();
        b.putSerializable("itemId", ItemId);
        intent.setClass(context, TbProductDetailActivity.class);
        intent.putExtras(b);
        context.startActivity(intent);
    }
}
